<?php

class SurveyParticipationController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('allow',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new SurveyParticipation;

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);
		
		$create_success = false;
		if(isset($_REQUEST['SurveyParticipation']))
		{
			$model->attributes=$_REQUEST['SurveyParticipation'];
			$create_success = $model->save();
		}

		if($create_success)
		{			
			$response = new ServerResponse(100, "Survey participation created.", $model);
		}
		else
		{
			$response = new ServerResponse(-100, "Could not create survey participation.", $model);
		}

		$this->renderJSON($response);
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate()
	{
		$id=$_REQUEST['SurveyParticipation']['id'];
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		$update_success = false;
		if(isset($_REQUEST['SurveyParticipation']))
		{
			$model->attributes=$_REQUEST['SurveyParticipation'];
			if($model->save())
				$update_success = true;
		}
		
		if($update_success)
		{			
			$response = new ServerResponse(100, "Survey participation updated.", $model);
		}
		else
		{
			$response = new ServerResponse(-100, "Could not update survey participation.", $model);
		}

		$this->renderJSON($response);
	}
	
	public function actionResults()
	{
		$survey_id=$_REQUEST['survey_id'];
		
		$participations = $this->loadCompletedSurveyParticipationModels($survey_id);
		
		foreach($participations as $participation)
		{
			$participation_details_model = $this->loadParticipationDetails($participation->id);
			
			//print_r($participation_details_model);
			
			foreach($participation_details_model as $participation_model)
			{	
				$participation_attempt = null;
				
				$participation_attempt->id = $participation_model->id;
				$participation_attempt->survey_participation_id = $participation_model->survey_participation_id;
				
				$participation_attempt->question_id = $participation_model->question_id;
				$participation_attempt->question_text = $participation_model->question->text;
				
				$participation_attempt->chosen_answer_id = $participation_model->chosen_answer_id;
				$participation_attempt->answer_text = $participation_model->chosenAnswer->text;
				
				$participation_details_list[] = $participation_attempt;
			}
			
			
		}
		
		$this->renderJSON($participation_details_list);
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('SurveyParticipation');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new SurveyParticipation('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['SurveyParticipation']))
			$model->attributes=$_GET['SurveyParticipation'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return SurveyParticipation the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=SurveyParticipation::model()->findByPk($id);
		return $model;
	}
	
	public function loadCompletedSurveyParticipationModels($survey_id)
	{
		
		$found = SurveyParticipation::model()->findAllByAttributes(
						array(),
						$condition  = 'survey_id = :survey_id AND is_complete = :is_complete',
						$params     = array(
											':survey_id' => $survey_id,
											':is_complete' => 1
										)
				);
		if($found)	
			return $found;
		else
			return null;
	}
	
	public function loadParticipationDetails($survey_participation_id)
	{
		$found = SurveyParticipationDetails::model()->with('question', 'chosenAnswer')->findAllByAttributes(
						array(),
						$condition  = 'survey_participation_id = :survey_participation_id',
						$params     = array(
											':survey_participation_id' => $survey_participation_id
										)
				);
		if($found)	
			return $found;
		else
			return null;
	}

	/**
	 * Performs the AJAX validation.
	 * @param SurveyParticipation $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='survey-participation-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
